<template>
  <view class="system-notification-page page-content">
    <z-paging ref="paging" v-model="notificationList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无通知">
      <template #top>
        <up-navbar title="系统通知" :autoBack="true" :fixed="true" bgColor="transparent" :border="false" placeholder>
          <template #right>
            <view class="navbar-actions">
              <up-button 
                size="mini" 
                type="primary" 
                plain
                @click="handleMarkAllRead"
                :disabled="unreadCount === 0"
              >
                全部已读
              </up-button>
            </view>
          </template>
        </up-navbar>
      </template>

      <!-- 筛选和搜索区域 -->
      <view class="filter-section">
        <view class="filter-row">
          <view class="filter-item">
            <up-dropdown ref="statusDropdown" :list="statusOptions" @change="handleStatusChange">
              <up-button size="small" plain suffix-icon="arrow-down">
                {{ currentStatusText }}
              </up-button>
            </up-dropdown>
          </view>
          <view class="filter-item">
            <up-dropdown ref="typeDropdown" :list="typeOptions" @change="handleTypeChange">
              <up-button size="small" plain suffix-icon="arrow-down">
                {{ currentTypeText }}
              </up-button>
            </up-dropdown>
          </view>
        </view>
        <view class="search-row">
          <up-search 
            v-model="searchKeyword" 
            placeholder="搜索通知标题或内容" 
            @search="handleSearch"
            @clear="handleSearchClear"
            :show-action="false"
          ></up-search>
        </view>
      </view>

      <!-- 统计信息 -->
      <view class="stats-section" v-if="totalCount > 0">
        <view class="stats-item">
          <text class="stats-label">总计:</text>
          <text class="stats-value">{{ totalCount }}</text>
        </view>
        <view class="stats-item">
          <text class="stats-label">未读:</text>
          <text class="stats-value unread">{{ unreadCount }}</text>
        </view>
      </view>

      <!-- 通知列表 -->
      <view class="notification-list">
        <NotificationItem 
          v-for="(item, index) in notificationList" 
          :key="item.id" 
          :notification="item" 
          @click="handleNotificationClick"
          @markRead="handleMarkRead"
        />
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getSystemNotifications, markNotificationRead, markAllNotificationsRead } from '@/api';
import NotificationItem from './components/NotificationItem.vue';

// z-paging 组件引用
const paging = ref(null);
const statusDropdown = ref(null);
const typeDropdown = ref(null);

// 通知列表数据
const notificationList = ref([]);
const totalCount = ref(0);
const unreadCount = ref(0);

// 筛选条件
const currentStatus = ref('all');
const currentType = ref('all');
const searchKeyword = ref('');

// 状态筛选选项
const statusOptions = ref([
  { text: '全部状态', value: 'all' },
  { text: '未读', value: 'unread' },
  { text: '已读', value: 'read' }
]);

// 类型筛选选项
const typeOptions = ref([
  { text: '全部类型', value: 'all' },
  { text: '任务', value: 'task' },
  { text: '通知', value: 'notice' },
  { text: '警告', value: 'warning' },
  { text: '系统', value: 'system' }
]);

// 当前状态文本
const currentStatusText = computed(() => {
  const option = statusOptions.value.find(item => item.value === currentStatus.value);
  return option ? option.text : '全部状态';
});

// 当前类型文本
const currentTypeText = computed(() => {
  const option = typeOptions.value.find(item => item.value === currentType.value);
  return option ? option.text : '全部类型';
});

// 获取系统通知列表
const queryList = async (pageNo, pageSize) => {
  try {
    const params = {
      pageNo,
      pageSize,
      status: currentStatus.value === 'all' ? undefined : currentStatus.value,
      type: currentType.value === 'all' ? undefined : currentType.value,
      keyword: searchKeyword.value || undefined
    };
    
    // 调用API获取通知列表
    const result = await getSystemNotifications(params);
    
    // 如果后端API尚未实现，使用以下模拟数据进行测试
    if (!result.data) {
      const mockData = generateMockData(pageNo, pageSize);
      paging.value.complete(mockData.list);
      totalCount.value = mockData.total;
      unreadCount.value = mockData.unreadCount;
    } else {
      paging.value.complete(result.data.list || []);
      totalCount.value = result.data.total || 0;
      unreadCount.value = result.data.unreadCount || 0;
    }
  } catch (error) {
    console.error('获取系统通知失败', error);
    paging.value.complete(false);
  }
};

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const allData = [
    {
      id: '1',
      title: '车辆核验任务待处理',
      content: '您有一个新的车辆核验任务需要处理，请及时查看。车牌号：粤B12345，申请时间：2023-08-15 10:30:25',
      createTime: '2023-08-15 10:30:25',
      type: 'task',
      status: 'unread',
      targetUrl: '/pages/vehicle-internal-verify/detail',
      targetParams: { taskId: '12345' }
    },
    {
      id: '2',
      title: '系统维护通知',
      content: '系统将于今晚22:00-23:00进行例行维护，请提前做好相关工作安排。维护期间系统将暂停服务。',
      createTime: '2023-08-14 16:45:12',
      type: 'system',
      status: 'read',
      targetUrl: '',
      targetParams: {}
    },
    {
      id: '3',
      title: '工单处理提醒',
      content: '您有3个工单即将超时，请尽快处理。包括设备故障工单2个，投诉工单1个。',
      createTime: '2023-08-14 09:15:30',
      type: 'warning',
      status: 'unread',
      targetUrl: '/pages/work-order/index',
      targetParams: {}
    },
    {
      id: '4',
      title: '车辆申诉待处理',
      content: '有新的车辆申诉需要您审核，请及时处理。申诉车牌：粤A88888，申诉原因：设备故障导致误扣费。',
      createTime: '2023-08-13 14:20:45',
      type: 'task',
      status: 'read',
      targetUrl: '/pages/order-appeal/index',
      targetParams: {}
    },
    {
      id: '5',
      title: '新功能上线通知',
      content: '系统新增"系统通知"功能，方便管理员及时了解待处理事项和系统消息。',
      createTime: '2023-08-12 11:05:18',
      type: 'notice',
      status: 'read',
      targetUrl: '',
      targetParams: {}
    },
    {
      id: '6',
      title: '泊位禁用审核通过',
      content: '您提交的泊位禁用申请已审核通过，泊位编号：P001-P010，禁用时间：2023-08-16 08:00 至 2023-08-16 18:00。',
      createTime: '2023-08-11 15:30:00',
      type: 'notice',
      status: 'unread',
      targetUrl: '/pages/my-pending/berth-disable/index',
      targetParams: {}
    },
    {
      id: '7',
      title: '设备异常报警',
      content: '停车场设备异常，设备编号：DEV001，异常类型：通信故障，请及时处理。',
      createTime: '2023-08-11 09:45:22',
      type: 'warning',
      status: 'unread',
      targetUrl: '/pages/work-order/fault/index',
      targetParams: { deviceId: 'DEV001' }
    }
  ];
  
  // 根据筛选条件过滤数据
  let filteredData = allData;
  
  if (currentStatus.value !== 'all') {
    filteredData = filteredData.filter(item => item.status === currentStatus.value);
  }
  
  if (currentType.value !== 'all') {
    filteredData = filteredData.filter(item => item.type === currentType.value);
  }
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filteredData = filteredData.filter(item => 
      item.title.toLowerCase().includes(keyword) || 
      item.content.toLowerCase().includes(keyword)
    );
  }
  
  const total = filteredData.length;
  const unreadCount = allData.filter(item => item.status === 'unread').length;
  const startIndex = (pageNo - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const list = filteredData.slice(startIndex, endIndex);
  
  return {
    list,
    total,
    unreadCount
  };
};

// 处理状态筛选变化
const handleStatusChange = (item) => {
  currentStatus.value = item.value;
  paging.value.reload();
};

// 处理类型筛选变化
const handleTypeChange = (item) => {
  currentType.value = item.value;
  paging.value.reload();
};

// 处理搜索
const handleSearch = () => {
  paging.value.reload();
};

// 处理搜索清空
const handleSearchClear = () => {
  searchKeyword.value = '';
  paging.value.reload();
};

// 处理通知点击事件
const handleNotificationClick = async (notification) => {
  // 如果是未读消息，先标记为已读
  if (notification.status === 'unread') {
    await handleMarkRead(notification);
  }
  
  // 如果有目标URL，则跳转到对应页面
  if (notification.targetUrl) {
    let url = notification.targetUrl;
    if (notification.targetParams && Object.keys(notification.targetParams).length > 0) {
      const params = Object.entries(notification.targetParams)
        .map(([key, value]) => `${key}=${value}`)
        .join('&');
      url = `${url}?${params}`;
    }
    
    uni.navigateTo({
      url,
      fail: (err) => {
        console.error('页面跳转失败', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }
};

// 处理单个通知标记已读
const handleMarkRead = async (notification) => {
  try {
    // 调用API标记已读
    await markNotificationRead(notification.id);
    
    // 更新本地数据
    const index = notificationList.value.findIndex(item => item.id === notification.id);
    if (index !== -1) {
      notificationList.value[index].status = 'read';
      unreadCount.value = Math.max(0, unreadCount.value - 1);
    }
    
    uni.showToast({
      title: '已标记为已读',
      icon: 'success'
    });
  } catch (error) {
    console.error('标记已读失败', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 处理全部标记已读
const handleMarkAllRead = async () => {
  if (unreadCount.value === 0) {
    uni.showToast({
      title: '没有未读消息',
      icon: 'none'
    });
    return;
  }
  
  uni.showModal({
    title: '确认操作',
    content: `确定要将所有${unreadCount.value}条未读消息标记为已读吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用API全部标记已读
          await markAllNotificationsRead();
          
          // 更新本地数据
          notificationList.value.forEach(item => {
            if (item.status === 'unread') {
              item.status = 'read';
            }
          });
          unreadCount.value = 0;
          
          uni.showToast({
            title: '全部已标记为已读',
            icon: 'success'
          });
        } catch (error) {
          console.error('全部标记已读失败', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 页面挂载时获取数据
onMounted(() => {
  // 初始加载数据由z-paging的auto属性自动触发
});
</script>

<style scoped lang="scss">
.system-notification-page {
  background-color: #f5f5f5;
}

.navbar-actions {
  padding-right: 20rpx;
}

.filter-section {
  background-color: #ffffff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.filter-item {
  flex: 1;
}

.search-row {
  width: 100%;
}

.stats-section {
  background-color: #ffffff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-around;
  border-radius: 12rpx;
}

.stats-item {
  text-align: center;
}

.stats-label {
  font-size: 24rpx;
  color: #999999;
  margin-right: 8rpx;
}

.stats-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  
  &.unread {
    color: #f5222d;
  }
}

.notification-list {
  padding: 0 20rpx;
}
</style>